package com.xyzboom.database.dao;

import com.xyzboom.database.entity.User;
import com.xyzboom.database.utils.DatabaseUtils;
import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.SQLException;

public class UserDAO {
    public static boolean userExists(String username, String school, String department) throws SQLException {
        return getUser(username, school, department) != null;
    }

    public static User getUser(String username, String school, String department) throws SQLException {
        return DatabaseUtils.getQueryRunner().query("select * from user " +
                        "where uName = ? and uSchool = ? and uDepartment = ?", getHandler(),
                username, school, department);
    }

    public static User getUser(int id) throws SQLException {
        return DatabaseUtils.getQueryRunner().query("select * from user " +
                "where uId=?", getHandler(), id);
    }

    public static boolean newUser(User user) throws SQLException {
        return DatabaseUtils.getQueryRunner().update(
                "INSERT INTO user (uId, uName, uPw, uSchool, uDepartment)\n" +
                        "VALUES (?, ?, ?, ?, ?);", user.getId(), user.getUsername(), user.getPassword(),
                user.getSchool(), user.getDepartment()) == 1;
    }

    public static ResultSetHandler<User> getHandler() {
        return rs -> {
            if (!rs.next()) {
                return null;
            }
            return new User(
                    rs.getInt("uId"),
                    rs.getString("uName"),
                    rs.getString("uPw"),
                    rs.getString("uSchool"),
                    rs.getString("uDepartment")
            );
        };
    }
}
